<template>
  <el-dialog
    v-model="dialogVisible"
    title="实例详情"
    width="50%"
    :close-on-click-modal="true"
    :close-on-press-escape="true"
    class="instance-detail-dialog"
  >
    <div class="instance-detail-content">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="实例ID">{{
          localInstance._id
        }}</el-descriptions-item>
        <el-descriptions-item label="实例名称">{{
          localInstance.name
        }}</el-descriptions-item>
        <el-descriptions-item label="IP地址">{{
          localInstance.ipAddress
        }}</el-descriptions-item>
        <el-descriptions-item label="端口">{{
          localInstance.port
        }}</el-descriptions-item>
        <el-descriptions-item label="运行工程">{{
          localInstance?.project?.originalName
        }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{
          new Date(localInstance.createdAt).toLocaleString()
        }}</el-descriptions-item>
        <el-descriptions-item label="GPU序号">{{
          localInstance.gpuId
        }}</el-descriptions-item>
        <el-descriptions-item label="渲染分辨率">{{
          localInstance.resolutionX + " x " + localInstance.resolutionY
        }}</el-descriptions-item>
        <el-descriptions-item label="连接状态">
          <el-tag :type="localInstance.isConnected ? 'success' : 'info'">
            {{ localInstance.isConnected ? "已连接" : "未连接" }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="运行状态">
          <el-tag :type="getStatusType(localInstance.status)">
            {{ getStatusText(localInstance.status) }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="localInstance.status === 'running'"
          type="primary"
          @click="handleTestInstance"
          >测试实例</el-button
        >
        <el-button
          v-if="localInstance.status === 'running'"
          type="primary"
          @click="handleRestartInstance"
          >重启实例</el-button
        >
        <el-button
          v-if="localInstance.status === 'running'"
          type="warning"
          @click="handleClearConnection"
          >清空连接</el-button
        >
        <el-button type="danger" @click="handleDeleteInstance"
          >删除实例</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
// 引入必要的函数
import { useRouter } from "vue-router";
import {
  deleteInstance,
  restartInstance,
  clearClient,
  getAvailableInstances,
} from "@/api/modules/ueInstance";
// 获取 Vue Router 实例
const router = useRouter();
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  instance: {
    type: Object,
    default() {
      return {};
    },
  },
});

const emit = defineEmits(["update:visible", "refresh"]);

// 控制对话框显示
const dialogVisible = ref(props.visible);

// 监听dialogVisible的变化
watch(
  () => dialogVisible.value,
  (newVal) => {
    emit("update:visible", newVal);
  }
);

// 监听props.visible的变化
watch(
  () => props.visible,
  (newVal) => {
    dialogVisible.value = newVal;
  }
);
// 创建本地实例数据的副本
const localInstance = ref({});
watch(
  () => props.instance,
  (newVal) => {
    // 深拷贝实例数据
    localInstance.value = JSON.parse(JSON.stringify(newVal));
  },
  { deep: true, immediate: true }
);
// // 模拟实例数据
// const instance = ref({});

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    running: "success",
    stopped: "info",
    error: "danger",
    starting: "primary",
    stopping: "warning",
    restarting: "primary",
    deleting: "danger",
  };
  return statusMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status) => {
  const statusTextMap = {
    running: "运行中",
    stopped: "已停止",
    error: "错误",
    starting: "启动中",
    stopping: "停止中",
    restarting: "重启中",
    deleting: "删除中",
  };
  return statusTextMap[status] || "未知";
};

// 清空连接
const handleClearConnection = async () => {
  try {
    await ElMessageBox.confirm("确定要清空该实例的连接吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    // TODO: 调用清空连接的API
    clearClient({ instanceId: props.instance._id })
      .then((res) => {
        const { data } = res;
        ElMessage.success(`实例:${data.name} 已清空连接`);
      })
      .catch((error) => {
        console.log(error);
        ElMessage.error("清空连接失败");
      })
      .finally(() => {
        emit("refresh");
      });
  } catch (error) {
    // 用户取消操作
  }
};

// 删除实例
const handleDeleteInstance = async () => {
  try {
    await ElMessageBox.confirm(
      "确定要删除该实例吗？此操作将直接删除实例，已连接状态用户也将断开连接，不可恢复！",
      "警告",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
      }
    );
    // TODO: 调用删除实例的API
    deleteInstance({ instanceId: props.instance._id })
      .then((res) => {
        const { data } = res;
        ElMessage.success(`实例:${data.name} 删除中`);
      })
      .catch((error) => {
        console.log(error);
        ElMessage.error("删除实例失败");
      })
      .finally(() => {
        dialogVisible.value = false;
        emit("refresh");
      });
  } catch (error) {
    // 用户取消操作
  }
};
const handleRestartInstance = async () => {
  try {
    await ElMessageBox.confirm("确定要重启该实例吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    restartInstance({ instanceId: props.instance._id })
      .then((res) => {
        const { data } = res;
        ElMessage.success(`实例:${data.name} 重启中`);
      })
      .catch((error) => {
        console.log(error);
        ElMessage.error("重启失败");
      })
      .finally(() => {
        emit("refresh");
      });
  } catch (error) {
    // 用户取消操作
  }
};
// 测试实例
const handleTestInstance = async () => {
  const instanceInfo = {
    url: `ws://${localInstance.value.ipAddress}:${localInstance.value.port}`,
    instanceId: localInstance.value._id,
    name: localInstance.value.name,
  };

  router.push({
    path: "/instance-demo",
    query: instanceInfo,
  });
};
</script>

<style scoped>
.instance-detail-dialog {
  .instance-detail-content {
    padding: 20px 0;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding-top: 20px;
  }

  :deep(.el-descriptions) {
    padding: 0 20px;
  }
}
</style>
